import com.speljohan.rsbot.account.Account;
import com.speljohan.rsbot.bot.Bot;
import com.speljohan.rsbot.script.Random;
import com.speljohan.rsbot.script.wrappers.RSInterface;

/**
 * LoginBot.java
 * 
 * Simple login bot made by Gnarly for RSBot
 * 
 * @author Gnarly
 */
public class LoginBot extends Random {

	private Account account;
	private int failSafeCount;

	@Override
	public boolean activateCondition() {
		account = Bot.getAccount();
		failSafeCount = 0;
		return !isLoggedIn();
	}

	@Override
	public String getAuthor() {
		return "Gnarly";
	}

	@Override
	public String getName() {
		return "LoginBot";
	}

	@Override
	public double getVersion() {
		return 1.0;
	}

	@Override
	public int loop() {
		if (isLoggedIn()) {
			return -1;
		} else {
			failSafeCount++;
		}
		if (RSInterface.getInterface(744).getChild(606).getText().contains("update") || RSInterface.getInterface(744).getChild(606).getText().contains("disable")) {
			stopAllScripts();
		}
		while (RSInterface.getInterface(744).getChild(606).getText().contains("world")) {
			wait(500);
		}
		int typingPropType = 0;
		if (isLoginScreen()) {
			int propTrys = 0;
			while (true) {
				propTrys++;
				if (RSInterface.getInterface(744).getChild(612).getText().endsWith("|")) {
					typingPropType = 1;
					break;
				}
				if (RSInterface.getInterface(744).getChild(618).getText().endsWith("|")) {
					typingPropType = 2;
					break;
				}
				if (propTrys == 50)
					break;
				wait(random(10, 20));
			}
			if (typingPropType == 0) {
				atInterface(744, 627);
			}
			if (typingPropType == 1) {
				sendUserProp(account.getUsername(), 612);
			}
			if (typingPropType == 2) {
				sendUserProp(account.getPassword(), 618);
			}
		}
		return random(250, 500);
	}

	private void sendUserProp(final String prop, final int type) {
		String boxText = RSInterface.getInterface(744).getChild(type).getText();
		if (boxText.endsWith("|")) {
			boxText = boxText.substring(0, boxText.length() - 1);
		}
		final int boxTextLength = boxText.length();
		if (boxTextLength == prop.length()) {
			sendText("", true);
			return;
		}
		if (boxTextLength > 0 && boxTextLength != prop.length()) {
			for (int i = 0; i <= boxTextLength; i++) {
				sendText("\b", false);
				wait(random(5, 10));
			}
		}
		sendText(prop, false);
		sendUserProp(prop, type);
	}

}